package api

import (
	"fmt"
	"go-weiqi-system/config"
	"go-weiqi-system/internal/models"
	"go-weiqi-system/internal/utils"
	"time"

	"github.com/gin-gonic/gin"
)

type OrderController struct{}

// CreateOrder 创建订单
func (ctrl *OrderController) CreateOrder(c *gin.Context) {
	userID, _ := c.Get("user_id")

	var req struct {
		Type      string `json:"type" binding:"required"`
		RelatedID uint   `json:"related_id" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Error(c, "参数错误")
		return
	}

	var relatedName string
	var amount float64

	// 根据类型获取相关信息
	if req.Type == "course" {
		var course models.Course
		if err := config.DB.First(&course, req.RelatedID).Error; err != nil {
			utils.Error(c, "课程不存在")
			return
		}
		relatedName = course.Title
		amount = course.Price
	} else {
		utils.Error(c, "不支持的订单类型")
		return
	}

	// 生成订单号
	orderNo := fmt.Sprintf("O%d%d", time.Now().Unix(), userID)

	// 创建订单
	order := models.Order{
		OrderNo:     orderNo,
		UserID:      userID.(uint),
		Type:        req.Type,
		RelatedID:   req.RelatedID,
		RelatedName: relatedName,
		Amount:      amount,
		Status:      "待支付",
	}

	if err := config.DB.Create(&order).Error; err != nil {
		utils.Error(c, "创建订单失败")
		return
	}

	utils.Success(c, order, "订单创建成功")
}

// MyOrders 我的订单列表
func (ctrl *OrderController) MyOrders(c *gin.Context) {
	userID, _ := c.Get("user_id")

	var param models.PageParam
	if err := c.ShouldBindQuery(&param); err != nil {
		param.Page = 1
		param.PageSize = 10
	}

	status := c.Query("status")

	var orders []models.Order
	var total int64

	db := config.DB.Model(&models.Order{}).Where("user_id = ?", userID)

	if status != "" {
		db = db.Where("status = ?", status)
	}

	db.Count(&total)
	db.Order("id desc").
		Offset(param.GetOffset()).
		Limit(param.GetPageSize()).
		Find(&orders)

	utils.Success(c, models.PageResponse{
		List:     orders,
		Total:    total,
		Page:     param.GetPage(),
		PageSize: param.GetPageSize(),
	})
}

// OrderDetail 订单详情
func (ctrl *OrderController) OrderDetail(c *gin.Context) {
	userID, _ := c.Get("user_id")
	orderID := c.Query("id")

	if orderID == "" {
		utils.Error(c, "参数错误")
		return
	}

	var order models.Order
	if err := config.DB.Where("id = ? AND user_id = ?", orderID, userID).First(&order).Error; err != nil {
		utils.Error(c, "订单不存在")
		return
	}

	utils.Success(c, order)
}

// CancelOrder 取消订单
func (ctrl *OrderController) CancelOrder(c *gin.Context) {
	userID, _ := c.Get("user_id")

	var req struct {
		ID uint `json:"id" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Error(c, "参数错误")
		return
	}

	var order models.Order
	if err := config.DB.Where("id = ? AND user_id = ?", req.ID, userID).First(&order).Error; err != nil {
		utils.Error(c, "订单不存在")
		return
	}

	if order.Status != "待支付" {
		utils.Error(c, "只能取消待支付的订单")
		return
	}

	if err := config.DB.Model(&order).Update("status", "已取消").Error; err != nil {
		utils.Error(c, "取消失败")
		return
	}

	utils.Success(c, nil, "取消成功")
}

// MockPay 模拟支付
func (ctrl *OrderController) MockPay(c *gin.Context) {
	userID, _ := c.Get("user_id")

	var req struct {
		ID uint `json:"id" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Error(c, "参数错误")
		return
	}

	var order models.Order
	if err := config.DB.Where("id = ? AND user_id = ?", req.ID, userID).First(&order).Error; err != nil {
		utils.Error(c, "订单不存在")
		return
	}

	if order.Status != "待支付" {
		utils.Error(c, "订单状态不正确")
		return
	}

	// 更新订单状态
	updates := map[string]interface{}{
		"status":     "已支付",
		"pay_time":   time.Now().Format("2006-01-02 15:04:05"),
		"pay_method": "模拟支付",
	}

	if err := config.DB.Model(&order).Updates(updates).Error; err != nil {
		utils.Error(c, "支付失败")
		return
	}

	// 如果是课程订单，添加到用户课程
	if order.Type == "course" {
		userCourse := models.UserCourse{
			UserID:   order.UserID,
			CourseID: order.RelatedID,
			OrderID:  order.ID,
		}
		config.DB.Create(&userCourse)
	}

	utils.Success(c, nil, "支付成功")
}
